package test;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import junit.framework.TestCase;

import org.webscale.ApplicationController;
import org.webscale.ApplicationException;

public abstract class BaseTestCase extends TestCase {
	public  static boolean reloadBetweenTestCases = false;
	private static Properties properties = null;
	private static boolean propLoaded = false;
	/**
	 * Place Holder to store any objects required between Test cases
	 */
	private static HashMap<String, Object> interTestCaseState = new HashMap<String, Object>();
	

	public abstract String propertiesFileLocations();
	
	protected void storeForLater(String key , Object obj){
		interTestCaseState.put(key, obj);
	}
	
	protected Object getFromStore(String key){
		return interTestCaseState.get(key);
	}
	
	protected void setUp() throws Exception {
		super.setUp();
		start();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		stop();
	}
	protected Object lookUp(String objName){
		return  ApplicationController.instance().locateObject(objName);
	}
	
	public void loadProp() {
		if (properties == null) {
			InputStream is = BaseTestCase.class.getClassLoader()
					.getResourceAsStream(propertiesFileLocations());
	//		logger.debug(propertiesFileLocation);
	//		logger.debug(" IS is " + is);
			try {
				properties = new Properties();
				properties.load(is);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(e);
			}
		}
	}

	
	public  void startUp() {
		start();
	}

	public  void shutDown() {
		if (reloadBetweenTestCases)
			stop();
	}

	public  void globalStop() {
		stop();
	}

	protected void start() {
		if (!propLoaded)
			loadProp();
		if (ApplicationController.instance().isRunning())
			return;
		try {
			String mode = properties.getProperty("application-run-mode");
			if(mode == null){
				mode = "test";
				properties.setProperty("application-run-mode", mode);
			}
			ApplicationController.instance().setStartUpParamenters(properties);
			ApplicationController.instance().init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected  void stop() {
		if (!ApplicationController.instance().isRunning())
			return;
		try {
		//	logger.info(" STOPPING CONTAINER.....");
			ApplicationController.instance().stop();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
